package com.boc.langxiang.ui.activity.shop;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.boc.langxiang.App;
import com.boc.langxiang.R;
import com.boc.langxiang.contract.shop.AddToShoppingCarContract;
import com.boc.langxiang.contract.shop.BuyNowContract;
import com.boc.langxiang.contract.shop.ProductCollectionContract;
import com.boc.langxiang.contract.shop.ProductCustomizeContract;
import com.boc.langxiang.contract.shop.ProductDetailView;
import com.boc.langxiang.entity.bean.PhotoBean;
import com.boc.langxiang.entity.bean.ProductDetailInfo;
import com.boc.langxiang.entity.request.AddToShoppingCarRequest;
import com.boc.langxiang.entity.request.ProductBuyRequest;
import com.boc.langxiang.entity.response.CollectionContent;
import com.boc.langxiang.entity.response.ProductBuyContent;
import com.boc.langxiang.entity.response.ProductCustomizeRequest;
import com.boc.langxiang.manager.PicassoImageLoader;
import com.boc.langxiang.presenter.AddToShoppingCarPresenter;
import com.boc.langxiang.presenter.shop.BuyNowPresenter;
import com.boc.langxiang.presenter.shop.ProductCollectionPresenter;
import com.boc.langxiang.presenter.shop.ProductCustomizePresenter;
import com.boc.langxiang.presenter.shop.ProductDetailPresenter;
import com.boc.langxiang.ui.activity.BaseToolBarActivity;
import com.boc.langxiang.ui.dialog.CustomizedResultDialog;
import com.boc.langxiang.ui.view.ProductPhotoPager;
import com.boc.langxiang.util.StringUtil;
import com.boc.langxiang.util.T;
import com.jakewharton.rxbinding.view.RxView;

import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;

/**
 * 产品详情
 */
public class ProductDetailActivity extends BaseToolBarActivity implements ProductDetailView, View.OnClickListener {
    @BindView(R.id.pager_view)
    ProductPhotoPager pagerView;
    @BindView(R.id.bottom_bar)
    LinearLayout bottomBar;
    //    @BindView(R.id.specification_selector)
//    SpecificationSelector specificationSelector;
    @BindView(R.id.products_title_tv)
    TextView productsTitleTv;
    @BindView(R.id.price_tv)
    TextView priceTv;
    @BindView(R.id.add_shoppingcar)
    RelativeLayout addShoppingcar;
    @BindView(R.id.buy_now)
    RelativeLayout buyNow;
    @BindView(R.id.model_tv)
    TextView modelTv;
    @BindView(R.id.remark_tv)
    TextView remarkTv;
    @BindView(R.id.goto_customize_btn)
    LinearLayout gotoCustomizeBtn;
    @BindView(R.id.zan_count)
    TextView mZanCount;
//    @BindView(R.id.stock_num_tv)
//    TextView stockNumTv;
//    @BindView(R.id.stock_layout)
//    RelativeLayout stockLayout;

    private AddToShoppingCarRequest mAddToShoppingCarRequest;

    private ProductBuyRequest mProductBuyRequest;

    private boolean clickAble = false;

    private String id;

//    private MenuItem mMenuItem;

    private Menu mActionMenu;

    private ProductDetailInfo mProductDetailInfo;

    private boolean mustSelectSize = false;
    private int mCollect;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_product_detail);
        ButterKnife.bind(this);
        if (getIntent() != null && getIntent().getStringExtra("id") != null) {
            id = getIntent().getStringExtra("id");
        }
        initViews();
    }

    private void initViews() {
        addShoppingcar.setOnClickListener(this);
        buyNow.setOnClickListener(this);
        gotoCustomizeBtn.setOnClickListener(this);
    }

    private void initData() {
        ProductDetailPresenter presenter = new ProductDetailPresenter(this);
        presenter.getContent(id);
        mAddToShoppingCarRequest = new AddToShoppingCarRequest();
        mProductBuyRequest = new ProductBuyRequest(id);
    }

    ProductPhotoPager.ImagePagerListener mImagePagerListener = new ProductPhotoPager.ImagePagerListener() {
        @Override
        public void displayImage(PhotoBean photo, ImageView imageView) {
            PicassoImageLoader.getInstance().displayUrlImage(mContext, photo.getUrl(), imageView);
        }

        @Override
        public void onImageClick(PhotoBean bean, int position, View imageView) {
            Intent intent = new Intent(mContext, PhotoDetailActivity.class);
            intent.putExtra("position", position);
            intent.putExtra("info", mProductDetailInfo);
            startActivity(intent);
        }
    };

    @Override
    protected void onCreateCustomToolBar(Toolbar toolbar) {
        super.onCreateCustomToolBar(toolbar);
        toolbar.setNavigationIcon(R.drawable.icon_return_black);
        toolbar.setBackgroundColor(Color.WHITE);
        setToolBarTitle("产品详情");
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_product_collection, menu);
        mActionMenu = menu;
        initData();
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_collection:
                if (isLogin()) {
                    onCollection(item);
                }
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    private void onCollection(final MenuItem item) {
        new ProductCollectionPresenter(new ProductCollectionContract.View() {
            @Override
            public void onSuccess(CollectionContent content) {
                switch (content.getRes()) {
                    case "0":
                        item.setIcon(R.drawable.icon_collected_false);
                        mCollect -= 1;
                        mZanCount.setText(mCollect + "");
                        Toast.makeText(mContext, "取消收藏", Toast.LENGTH_SHORT).show();
                        break;
                    case "1":
                        item.setIcon(R.drawable.icon_collected_true);
                        mCollect += 1;
                        mZanCount.setText(mCollect + "");
                        Toast.makeText(mContext, "收藏成功", Toast.LENGTH_SHORT).show();
                        break;
                    case "2":
                        T.showShort(mContext, "操作失败");
                        break;
                }
            }

            @Override
            public void showLoading() {
                showProgressDialog("收藏中，请稍等....");
            }

            @Override
            public void hideLoading() {
                hideDialog();
            }

            @Override
            public void onError(String code, String msg) {
                T.showShort(mContext, msg);
            }
        }).collect(id);
    }

    @Override
    protected boolean isSetTypeFace() {
        return true;
    }

    @Override
    protected boolean isToolBarDividerVisible() {
        return false;
    }

    @Override
    public void getDetailSuccess(final ProductDetailInfo info) {
        clickAble = true;
        mProductDetailInfo = info;
        productsTitleTv.setText(info.getTitle());
        pagerView.setPhotos(info.getPhoto(), mImagePagerListener);

        priceTv.setText(info.getPrice());
        remarkTv.setText(info.getRemark());
        modelTv.setText(info.getXinghao());
        mCollect = info.getCollect();
        mZanCount.setText(mCollect + "");

//        if (info.getMore().size() > 0) {
//            if (StringUtil.isEmpty(info.getMore().get(0).getSize())) {
//                stockLayout.setVisibility(View.VISIBLE);
//                stockNumTv.setText(info.getMore().get(0).getNum());
//                mustSelectSize = false;
//            } else {
//                mustSelectSize = true;
//                stockLayout.setVisibility(View.GONE);
//                String[] sizes = new String[info.getMore().size()];
//                List<Integer> cannotSelectPosition = new ArrayList<>();
//                for (int i = 0; i < info.getMore().size(); i++) {
//                    sizes[i] = info.getMore().get(i).getSize().toUpperCase();
//                    if (info.getMore().get(i).getNum().equals("0")) {
//                        cannotSelectPosition.add(i);
//                    }
//                }
//                specificationSelector.setTabTitles(sizes);
//                specificationSelector.setOnSpecificationSelectListener(new SpecificationSelector.OnSpecificationSelectListener() {
//                    @Override
//                    public void onSelected(int position, String title) {
//                        mAddToShoppingCarRequest.setSize(title);
//                        mProductBuyRequest.setSize(title);
//                    }
//
//                    @Override
//                    public void onFailed(int position, String title) {
//
//                    }
//                });
//                if (cannotSelectPosition.size() > 0) {
//                    int[] unSelectAbles = new int[cannotSelectPosition.size()];
//                    for (int i = 0; i < cannotSelectPosition.size(); i++) {
//                        unSelectAbles[i] = cannotSelectPosition.get(i);
//                    }
//                    specificationSelector.setCannotSelectTAbs(unSelectAbles);
//                }
//            }
//        }

        if (mActionMenu != null && !StringUtil.isEmpty(info.getCollect_status())) {
            switch (info.getCollect_status()) {
                case "0":
                    mActionMenu.findItem(R.id.action_collection).setIcon(R.drawable.icon_collected_false);
                    break;
                case "1":
                    mActionMenu.findItem(R.id.action_collection).setIcon(R.drawable.icon_collected_true);
                    break;
            }
        }

    }

    @Override
    public void showLoading() {
        showProgressDialog("加载中");
    }

    @Override
    public void hideLoading() {
        hideDialog();
    }

    @Override
    public void onError(String code, String msg) {
        T.showShort(this, msg);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.add_shoppingcar:
                if (clickAble && isLogin()) {
                    addToShoppingCar();
                }
                break;
            case R.id.buy_now:
                if (isLogin()) {
                    if (clickAble) {
                        View cancelView = View.inflate(mContext, R.layout.popwindow_orders_cancel, null);
                        TextView message = (TextView) cancelView.findViewById(R.id.message);
                        TextView giveup = (TextView) cancelView.findViewById(R.id.atv_me_orders_giveup);
                        TextView sure = (TextView) cancelView.findViewById(R.id.atv_me_orders_sure);

                        message.setText("商品运费及安装费用需另行支付");
                        sure.setText("知道啦");
                        final PopupWindow cancelPopupWindow = new PopupWindow(cancelView, (int) (App.getInstance().getResources().getDisplayMetrics().widthPixels * 0.8), LinearLayout.LayoutParams.WRAP_CONTENT);
                        cancelPopupWindow.setAnimationStyle(R.style.me_pop_anim_center_style);
                        cancelPopupWindow.setFocusable(true);
                        cancelPopupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
                        cancelPopupWindow.setOutsideTouchable(true);
                        cancelPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                            @Override
                            public void onDismiss() {
                                setBackgroundAlpht(1f);
                            }
                        });
                        RxView.clicks(cancelPopupWindow.getContentView().findViewById(R.id.atv_me_orders_sure)).throttleFirst(2000, TimeUnit.MILLISECONDS).observeOn(AndroidSchedulers.mainThread())
                                .subscribe(new Action1<Void>() {
                                    @Override
                                    public void call(Void aVoid) {
                                        cancelPopupWindow.dismiss();
                                        buyNow();
                                    }
                                });
                        RxView.clicks(cancelPopupWindow.getContentView().findViewById(R.id.atv_me_orders_giveup)).throttleFirst(2000, TimeUnit.MILLISECONDS).observeOn(AndroidSchedulers.mainThread())
                                .subscribe(new Action1<Void>() {
                                    @Override
                                    public void call(Void aVoid) {
                                        cancelPopupWindow.dismiss();
                                    }
                                });
                        cancelPopupWindow.showAtLocation(cancelView, Gravity.CENTER, 0, 0);
                        setBackgroundAlpht(0.5f);
                    }
                }
                break;

            case R.id.goto_customize_btn:
                customize();
                break;
        }
    }

    private void setBackgroundAlpht(float value) {
        WindowManager.LayoutParams attributes = getWindow().getAttributes();
        attributes.alpha = value;
        getWindow().setAttributes(attributes);
    }

    private void customize() {
        if (!isLogin()) {
            return;
        } else {
            ProductCustomizeRequest request = new ProductCustomizeRequest();
            request.setPid(mProductDetailInfo.getId());
            request.setContent(mProductDetailInfo.getRemark());
            request.setTitle(mProductDetailInfo.getTitle());
            new ProductCustomizePresenter(new ProductCustomizeContract.View() {
                @Override
                public void onSuccess() {
                    new CustomizedResultDialog(mContext).show();
                }

                @Override
                public void showLoading() {
                    ProductDetailActivity.this.showLoading();
                }

                @Override
                public void hideLoading() {
                    ProductDetailActivity.this.hideDialog();
                }

                @Override
                public void onError(String code, String msg) {
                    ProductDetailActivity.this.onError(code, msg);
                }
            }).customize(request);
        }
    }

    private void addToShoppingCar() {
        if (!isLogin()) {
            return;
        }
        mAddToShoppingCarRequest.setNumber("1");
        mAddToShoppingCarRequest.setPid(mProductDetailInfo.getId());
        mAddToShoppingCarRequest.setTitle(mProductDetailInfo.getTitle());
        mAddToShoppingCarRequest.setPhoto(mProductDetailInfo.getPhoto().get(0).getId());
        mAddToShoppingCarRequest.setTypeId(AddToShoppingCarRequest.PRODUCT);
        if (mustSelectSize) {
            if (StringUtil.isEmpty(mAddToShoppingCarRequest.getSize())) {
                T.showShort(mContext, "请选择规格尺寸");
                return;
            }
        }
        mAddToShoppingCarRequest.setPrice(mProductDetailInfo.getPrice());
        new AddToShoppingCarPresenter(new AddToShoppingCarContract.View() {
            @Override
            public void onSuccess() {
                T.showShort(mContext, "添加购物车成功");
            }

            @Override
            public void showLoading() {
                showProgressDialog("正在处理，请稍候...");
            }

            @Override
            public void hideLoading() {
                hideDialog();
            }

            @Override
            public void onError(String code, String msg) {
                T.showShort(mContext, msg);
            }
        }).add(mAddToShoppingCarRequest);

    }

    private void buyNow() {
        BuyNowContract.Presenter presenter = new BuyNowPresenter(new BuyNowContract.View() {
            @Override
            public void onSuccess(ProductBuyContent content) {
//                if (StringUtil.isEmpty(content.getCartid())) {
//                    OrderInfo orderInfo = new OrderInfo();
//                    orderInfo.setAid(content.getOrder().getAid());
//                    orderInfo.setOrderid(content.getOrder().getOrderid());
//                    orderInfo.setPrice(content.getOrder().getPrice());
//                    new OrderPayDialog(mContext, orderInfo).show();
//                } else {
                String ids = content.getCartid();
                Intent intent = new Intent(mContext, OrderConfirmActivity.class);
                intent.putExtra("ids", ids);
                startActivity(intent);
//                }
            }

            @Override
            public void showLoading() {
                showProgressDialog("正在操作，请稍候...");
            }

            @Override
            public void hideLoading() {
                hideDialog();
            }

            @Override
            public void onError(String code, String msg) {
                T.showShort(mContext, msg);
            }
        });
//        if (mustSelectSize) {
//            if (StringUtil.isEmpty(mProductBuyRequest.getSize())) {
//                T.showShort(mContext, "请选择规格尺寸");
//                return;
//            }
//        }
        presenter.buyNow(mProductBuyRequest);
    }
}
